
import os
import sys
import shlex
from pathlib import Path

BASE_DIR = Path(__file__).resolve().parent.parent
sys.path.append(os.path.dirname(os.path.dirname(os.path.realpath(__file__))))

from utils.pyssh import  SSHProxy
from utils.custom_argparse import parse_args
from utils.custom_log import log_start
logger = log_start('main')

def bash(cmd):
    """ 执行bash命令 """
    logger.info(cmd)
    return shlex.os.system(cmd)


def exec_cmd(adminkey,remote_user,password,port):
    """ 远程执行命 """

    lst = []
    
    if os.path.exists(adminkey) is False:
        bash("ssh-keygen -f $HOME/.ssh/id_rsa -t rsa -N ''")
    
    with open(adminkey) as f:
        r_sshkeys = f.read().strip() # 读取key
    
    authorized_keys =  '$HOME/.ssh/authorized_keys'
    cmd1 = "mkdir  $HOME/.ssh && chmod 700 $HOME/.ssh"
    cmd2 = "grep admin.pem {1}|| echo '{0}' >> {1} ".format(r_sshkeys,authorized_keys)
    cmd3 = "sed -i '/admin.pem/c {0}'  {1}".format(r_sshkeys,authorized_keys)
    cmd = "{0} ; {1} ; {2} ;chmod 600 $HOME/.ssh/authorized_keys".format(cmd1,cmd2,cmd3)    
    
    hostsfile = os.path.join(BASE_DIR, 'config/hosts.txt')
    with open(hostsfile) as f:
        for line in f:
            line = line.strip().split()
            if password:
                passwd = password
            else:
                passwd =line[1]
            host = line[0]

            try:
                with SSHProxy(host, port, remote_user, passwd) as ssh:
                    ssh.command(cmd)
            except Exception as e:
                lst.append(host)

    if lst:
        logger.error(f'推送失败主机数量: {len(lst)}; 列表:\n{lst}')
    info =f"{r_sshkeys} \n{authorized_keys}"
    logger.info(info)
    return lst



if __name__ == '__main__':
    # logger.error("test")
    if len(sys.argv) == 1:
        """ 如果没有传参则打印帮助信息 """
        sys.argv.append("--help")
        parse_args()
        sys.exit(0)

    params = parse_args()  # 获取传入的参数
    exec_cmd(params.sshkey,params.username,params.password,params.port)

    logger.info("推送完毕")